import datetime

from django import template

register = template.Library()


@register.filter
def time_format(value: datetime.datetime):
    now = datetime.datetime.now()
    time = ''
    if value.hour < 6:
        time = '凌晨'
    elif value.hour < 11:
        time = '上午'
    elif value.hour < 14:
        time = '中午'
    elif value.hour < 18:
        time = '下午'
    elif value.hour < 23:
        time = '晚上'
    else:
        time = '午夜'
    time = value.strftime(f'{time}%H:%M')
    date = ''
    if value.date() != now.date():
        last_day = datetime.timedelta(days=-1)
        yesterday = now + last_day
        the_day_before_yesterday = yesterday + last_day
        if value.date() == yesterday.date():
            date = '昨天 '
        elif value.date() == the_day_before_yesterday.date():
            date = '前天 '
        else:
            date = value.strftime('%Y年%m月%d日 ')
    return date + time
